package com.ikangtai.shecare.main;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.daimajia.androidanimations.library.Techniques;
import com.daimajia.androidanimations.library.YoYo;
import com.github.jorgecastillo.FillableLoader;
import com.ikangtai.shecare.R;
import com.ikangtai.shecare.common.App;
import com.ikangtai.shecare.common.baseView.guide.GuideActivity;
import com.ikangtai.shecare.common.db.DBManager;
import com.ikangtai.shecare.common.eventBusMsg.InitMemMsg;
import com.ikangtai.shecare.common.util.AppLog;
import com.ikangtai.shecare.personal.LoginActivity;
import com.nineoldandroids.animation.Animator;
import com.umeng.analytics.MobclickAgent;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subcriber;

import java.util.Locale;

import cn.jpush.android.api.JPushInterface;
import io.codetail.animation.SupportAnimator;
import io.codetail.animation.ViewAnimationUtils;


public class SplashActivity extends AppCompatActivity {
    //private WebView webview;
    private Intent intent;
    private long startSplashTime;
    private long endSplashTime;
    private static final long SPLASH_TIME = 1 * 200;
    private DBManager dbManager;
    private ImageView icon_img;

    private FrameLayout splash_center;
    private RelativeLayout mRlReveal;
    private ImageView mTxtTitle, splash_logo;
    private FillableLoader mPathLogo;


    private ConfigSplash mConfigSplash;
    private boolean hasAnimationStarted = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent intent = getIntent();

        boolean appKilled = false;
        if (intent != null)
            appKilled = intent.getBooleanExtra("appKilled", false);

        if (appKilled)
            AppLog.i("shecare is killed by Android OS! now begin reStart!");
        else
            AppLog.i("shecare normally start!");

        if (!appKilled && !isTaskRoot()) {
            finish();
            return;
        }

        App.appKilledFlag = 0;

        /*set it to be no title*/

        /*set it to be full screen*/
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        setContentView(R.layout.activity_splash);

        App.activityList.add(this);
        EventBus.getDefault().register(this);

        mConfigSplash = new ConfigSplash();
        initSplash(mConfigSplash);
        initUI();
        startSplashTime = System.currentTimeMillis();

        dbManager = new DBManager(getApplicationContext());
        App.userName = App.getStringUserPreference(App.SHARED_PREF_USER_NAME);
        App.userPswd = dbManager.getSqliteKeyValue(App.userName, "userPswd");
        App.authToken = App.getStringUserPreference(App.SHARED_PREF_USER_TOKEN);

    }


    public void initUI() {
        setContentView(R.layout.activity_splash);
        splash_center = (FrameLayout) findViewById(R.id.splash_center);
        mRlReveal = (RelativeLayout) findViewById(R.id.rlColor);
        mTxtTitle = (ImageView) findViewById(R.id.txtTitle);
        splash_logo = (ImageView) findViewById(R.id.splash_logo);
    }


    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus && !hasAnimationStarted) {
            startCircularReveal();
        }
    }


    public void startCircularReveal() {

        // get the final radius for the clipping circle
        int finalRadius = Math.max(mRlReveal.getWidth(), mRlReveal.getHeight()) + mRlReveal.getHeight() / 2;
        //bottom or top
        int y = UIUtil.getRevealDirection(mRlReveal, mConfigSplash.getRevealFlagY());
        //left or right
        int x = UIUtil.getRevealDirection(mRlReveal, mConfigSplash.getRevealFlagX());

        mRlReveal.setBackgroundResource(mConfigSplash.getBackgroundImg());
        SupportAnimator animator = ViewAnimationUtils.createCircularReveal(mRlReveal, x, y, 0, finalRadius);
        animator.setInterpolator(new AccelerateDecelerateInterpolator());
        animator.setDuration(mConfigSplash.getAnimCircularRevealDuration());
        animator.addListener(new SupportAnimator.AnimatorListener() {
            @Override
            public void onAnimationStart() {
            }

            @Override
            public void onAnimationCancel() {
            }

            @Override
            public void onAnimationRepeat() {
            }

            @Override
            public void onAnimationEnd() {
                startTextAnimation();
            }
        });
        animator.start();
        hasAnimationStarted = true;
    }


    public void startTextAnimation() {
        splash_center.setBackgroundResource(mConfigSplash.getImgDetails());
        splash_center.setVisibility(View.VISIBLE);
        YoYo.with(mConfigSplash.getAnimTitleTechnique()).withListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                animationsFinished();
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        }).duration(mConfigSplash.getAnimTitleDuration()).playOn(splash_center);
    }


    private void doSplash() {

        if (App.userName != null) {
            initAndGetIn();
        } else {
            if (App.getBooleanUserPreference("isFirstRun"))
                intent = new Intent(SplashActivity.this, GuideActivity.class);
            else
                intent = new Intent(SplashActivity.this, LoginActivity.class);

            startActivity(intent);
            finish();
        }
    }

    private void initAndGetIn() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                doInitWork();
                EventBus.getDefault().post(new InitMemMsg());

            }
        }).start();
    }

    private void doInitWork() {
        initCollectionIDsIntoMemory();
        initUserPreferencesIntoMemory();
        initDayUnitDSOutputsListIntoMemory();
    }

    private void initCollectionIDsIntoMemory() {
        dbManager.initCollectionIDs2Memory(App.userName);
    }

    private void initUserPreferencesIntoMemory() {
        dbManager.initUserPreferences2Memory(App.userName);
    }

    private void initDayUnitDSOutputsListIntoMemory() {
        dbManager.initDayUnitDSOutputsList2Memory(App.userName);
    }

    @Subcriber
    private void splashIn(InitMemMsg initMemMsg) {
        //initWebview();

        endSplashTime = System.currentTimeMillis();
        long splashedTime = endSplashTime - startSplashTime;
        AppLog.i("startSplashTime = " + startSplashTime + ", endSplashTime = " + endSplashTime + ", splashedTime = " + splashedTime);

        if (splashedTime < SPLASH_TIME) {
            long leftTime = SPLASH_TIME - splashedTime;

            new Handler().postDelayed(new Runnable() {
                public void run() {
                    AppLog.i("splash timeout! getInMainActivity now!");
                    getInMainActivity();
                }
            }, leftTime + 1000); //leftTime for release
        } else
            getInMainActivity();
    }

//    private void initWebview() {
//        webview = (WebView) findViewById(R.id.webview);
//        WebViewCfg webViewCfg = new WebViewCfg(webview);
//        webview = webViewCfg.getCfgedWebView(this, false);
//
//        AppLog.i("hxiao SplashActivity initData.html");
//        webview.addJavascriptInterface(new CustomerData(this, App.userName), "CustomerData");
//        webview.loadUrl("file:///android_asset/health/initData.html");
//    }

    private void getInMainActivity() {
        intent = new Intent(SplashActivity.this, MainActivity.class);
        startActivity(intent);
        //finish();
    }

    @Override
    protected void onResume() {
        super.onResume();
        JPushInterface.onResume(this);
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        JPushInterface.onPause(this);
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    public void initSplash(ConfigSplash configSplash) {
        switch (Locale.getDefault().getLanguage()) {
            case "zh":
                configSplash.setBackgroundImg(R.drawable.splash); //any color you want form colors.xml
                configSplash.setImgDetails(R.drawable.splash_text); //or any other drawable
                break;
            default:
                configSplash.setImgDetails(R.drawable.splash); //or any other drawable
                configSplash.setImgDetails(R.drawable.splash_en); //or any other drawable
                configSplash.setBackgroundImg(R.drawable.splash_text_en); //any color you want form colors.xml

        }
        configSplash.setAnimCircularRevealDuration(1000); //int ms
        configSplash.setRevealFlagX(Flags.REVEAL_RIGHT);  //or Flags.REVEAL_LEFT
        configSplash.setRevealFlagY(Flags.REVEAL_BOTTOM); //or Flags.REVEAL_TOP
        configSplash.setAnimTitleDuration(1000);
        configSplash.setAnimTitleTechnique(Techniques.SlideInUp);

    }

    public void animationsFinished() {
        startSplashTime = System.currentTimeMillis();

        dbManager = new DBManager(getApplicationContext());
        App.userName = App.getStringUserPreference(App.SHARED_PREF_USER_NAME);
        App.userPswd = dbManager.getSqliteKeyValue(App.userName, "userPswd");
        App.authToken = App.getStringUserPreference(App.SHARED_PREF_USER_TOKEN);

        doSplash();
    }

}
